<?php

namespace app\common\service;

use app\common\service\queue\User;
use EasyTask\Table;
use EasyTask\Task as EasyTask;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;

class ToolQueue extends Command
{

    const VERSION = '0.0.1';

    protected function configure()
    {
        //设置名称为task
        $this->setName('tool')
            //增加一个命令参数
            ->addArgument('action', Argument::OPTIONAL, "action", '')
            ->addArgument('data', Argument::OPTIONAL, "data", '');
    }

    protected function execute(Input $input, Output $output)
    {
        //获取输入参数
        $action = trim($input->getArgument('action'));
        $data = trim($input->getArgument('data'));
        $usedPushTask = 1;
        $task = new EasyTask;
        $task->setDaemon(true);
        $task->setAutoRecover(true);
        $task->setPrefix('STQueue');
        $task->setRunTimePath(RUNTIME_PATH);
        $task->addFunc(function () {
            $userQueue = new User();
            $userQueue->update_user_handle();
            $userQueue->update_free_meal_handle();
        }, 'UserQueue', 5, 1);

        switch ($action) {
            case 'start':
                $output->writeln("正在启动ST队列服务...");
                $output->writeln("STQueue version:" . static::VERSION);
                $task->start();
                break;
            case 'status':
                $output->writeln("ST队列服务状态");
                $output->writeln("STQueue version:" . static::VERSION);
                $task->status();
                break;
            case 'stop':
                $output->writeln("正在停止ST队列服务...");
                $task->stop(($data == 'f'));
                break;
            default:
                if (!in_array($action, ['?']))
                    $output->writeln("<error>不存在命令:{$action}</error>");
                $output->writeln("STQueue version:" . static::VERSION);
                $Table = new Table();
                $Table->setStyle('borderless');
                $Table->setHeader(['Command', 'Description']);
                $Table->addRow(['start', '启动']);
                $Table->addRow(['status', '查看队列运行状态']);
                $Table->addRow(['stop', '停止队列']);
                $Table->addRow(['stop f', '强制停止队列']);
                $output->writeln($Table->render());
                break;
        }
    }

}